package com.opensource.svgaplayer.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * ex.
 *
 * @author wl
 * @since 2021-06-28
 */
public class Pools {
    private Pools() {
    }

    public interface Pool<T> {
        T acquire();

        /**
         * release
         *
         * @param instance T
         * @return boolean
         */
        boolean release(T instance);
    }


    public static class SimplePool<T> implements Pool<T> {
        private int maxPoolSize;
        private List<Object> mPool;
        private int mPoolSize = 0;

        /**
         * SimplePool
         *
         * @param maxPoolSize int
         */
        public SimplePool(int maxPoolSize) {
            this.maxPoolSize = maxPoolSize;
            init();
        }

        private void init() {
            boolean isUP0 = maxPoolSize > 0;
            if (!isUP0) {
                String var6 = "The max pool size must be > 0";
                throw new IllegalArgumentException(var6);
            } else {
                this.mPool = new ArrayList<>(maxPoolSize);
            }
        }

        /**
         * acquire
         *
         * @return T
         */
        @Override
        public T acquire() {
            if (this.mPoolSize > 0) {
                int lastPooledIndex = this.mPoolSize - 1;
                Object instance = this.mPool.get(lastPooledIndex);
                this.mPool.set(lastPooledIndex, null);
                mPoolSize--;
                return (T) instance;
            } else {
                return null;
            }
        }

        /**
         * release
         *
         * @param instance T
         * @return boolean
         */
        @Override
        public boolean release(T instance) {
            boolean isInPool = !this.isInPool(instance);
            if (!isInPool) {
                String var6 = "Already in the pool!";
                throw new IllegalStateException(var6);
            }
            if (mPoolSize < this.mPool.size()) {
                mPool.set(mPoolSize, instance);
                return true;
            } else {
                return false;
            }
        }

        /**
         * isInPool
         *
         * @param instance T
         * @return boolean
         */
        private boolean isInPool(T instance) {
            for (int i = 0; i < mPoolSize; i++) {
                if (mPool.get(i) == instance) {
                    return true;
                }
            }
            return false;
        }
    }
}
